package com.kehutong.charge.admin;

import com.kehutong.charge.entity.ChargeUrgingConfig;
import com.kehutong.charge.entity.ChargeUrgingManage;
import com.kehutong.charge.service.ChargeUrgingService;
import com.kehutong.charge.util.enums.ChargeUrgingLadderEnum;
import com.kehutong.charge.util.enums.UrgingTypeEnum;
import com.kehutong.common.DeptService;
import com.kehutong.common.DoveClient;
import com.kehutong.common.dto.DeptDTO;
import com.kehutong.common.enums.TemplateType;
import com.kehutong.common.util.Token;
import org.coraframework.authz.HasPermission;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONArray;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.mvc.MvcAction;
import org.coraframework.mvc.http.Bean;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.orm.Pool;
import org.coraframework.orm.util.Enums;
import org.coraframework.util.Objects;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @program: kht
 * @description: 催费配置
 * @author: joneron
 * @create: 2021/6/23
 **/
@MvcAction
@ReqMapping("/admin/pay/charge/urging")
public class ChargeUrgingController {

    private static final Logger logger = LoggerFactory.getLogger(ChargeUrgingController.class);

    @Inject
    DeptService deptService;

    @Inject
    ChargeUrgingService chargeUrgingService;

    @Inject
    DoveClient doveClient;

    @ReqMapping("/config/init")
    public Object configInit() throws Exception {
        chargeUrgingService.configInit();
        return Result.success();
    }

    @ReqMapping("/page")
    @HasPermission("pay:charge:urging:view")
    public Object page(JSONObject jsonObject) throws Exception {
        return chargeUrgingService.findPage(jsonObject);
    }

    @ReqMapping("/pageUrging")
    @HasPermission("pay:charge:urging:view")
    public Object pageUrging(JSONObject jsonObject) throws Exception {
        return chargeUrgingService.findUrgingPage(jsonObject);
    }


    @ReqMapping("/pageUrging/export")
    @HasPermission("pay:charge:urging:view")
    public void pageUrgingExport(HttpServletRequest req, HttpServletResponse resp, JSONObject jsonObject){
        chargeUrgingService.pageUrgingExport(req,resp,jsonObject);
    }


    @ReqMapping("/list")
    @HasPermission("pay:charge:urging:view")
    public Object list(JSONObject jsonObject) {
        return chargeUrgingService.findList(jsonObject);
    }

    @Bean(newInstance=true, copy=true)
    @HasPermission("pay:charge:urging:edit")
    @ReqMapping("/save")
    public Object save(ChargeUrgingConfig entity, Token token) throws Exception {
        entity.setCreateName(token.getUsername());
        List<String> departList = token.getDepartments();
        if(null != departList && departList.size() > 0){
            logger.error("用户{}数据异常，部门为空！",token.getUsername());
            DeptDTO deptDTO = deptService.getDept(departList.get(0));
            entity.setDepartmentNo(deptDTO.getDepartmentNo());
            entity.setDepartmentNos(deptDTO.getDepartmentNos());
            entity.setDepartmentName(deptDTO.getDepartmentName());
        }

        return chargeUrgingService.save(entity);
    }

    @ReqMapping("/check")
    public Object check(JSONObject jsonObject){
        String urgingDateId = jsonObject.getString("urgingDateId");
        String communityNo = jsonObject.getString("communityNo");
        if (Objects.isEmpty(urgingDateId) || Objects.isEmpty(communityNo)) {
            return Result.error(0, "请填写必填参数");
        }
        ChargeUrgingLadderEnum ladderEnum = Enums.getEnum(ChargeUrgingLadderEnum.class, urgingDateId);
        List<ChargeUrgingConfig> configs = chargeUrgingService.getChargeUrgingConfigs(ladderEnum, communityNo);
        if (Objects.nonEmpty(configs)) {
            return Result.error(0, "已存在该时段催缴设置");
        }

        return Result.success();
    }

    @HasPermission("pay:charge:urging:edit")
    @ReqMapping("/batchSave")
    public Object batchSave(Token token, JSONObject jsonObject) throws Exception {
        String communityNo = jsonObject.getString("communityNo");
        String communityName = jsonObject.getString("communityName");
        JSONArray list = jsonObject.getJSONArray("list");

        if (org.coraframework.util.Objects.isEmpty(list)) {
            return Result.error(0, "请选择催费类型");
        }

        List<String> departList = token.getDepartments();
        for (int i = 0; i < list.size(); i++) {
            ChargeUrgingConfig config = Pool.newInstance(ChargeUrgingConfig.class);
            config.setCreateName(token.getUsername());
            // 设置权限
            if(null != departList && departList.size() > 0) {
                logger.error("用户{}数据异常，部门为空！",token.getUsername());
                DeptDTO deptDTO = deptService.getDept(departList.get(0));
                config.setDepartmentNo(deptDTO.getDepartmentNo());
                config.setDepartmentNos(deptDTO.getDepartmentNos());
                config.setDepartmentName(deptDTO.getDepartmentName());
            }

            config.setCommunityNo(communityNo);
            config.setCommunityName(communityName);

            JSONObject temp = list.getJSONObject(i);

            String urgingDateId = temp.getString("urgingDateId");
            ChargeUrgingLadderEnum ladderEnum = Enums.getEnum(ChargeUrgingLadderEnum.class, urgingDateId);
            config.setUrgingDate(ladderEnum);

            // String urgingTypeMsgId = temp.getString("urgingTypeMsgId");
            // UrgingTypeEnum urgingTypeMsg = Enums.getEnum(UrgingTypeEnum.class, urgingTypeMsgId);
            // config.setUrgingTypeMsg(urgingTypeMsg);

            List<String> typeMsgList = JSONObject.parseArray(temp.getJSONArray("typeMsgList").toString(),String.class);
            config.setTypeMsgList(typeMsgList);

            chargeUrgingService.save(config);
        }

        return Result.success();
    }


    @Bean(newInstance=true, copy=true)
    @HasPermission("pay:charge:urging:edit")
    @ReqMapping("/saveUrging")
    public Object saveUrging(ChargeUrgingManage entity, Token token) throws Exception {
        entity.setCreateName(token.getUsername());
        List<String> departList = token.getDepartments();
        if(null != departList && departList.size() > 0){
            logger.error("用户{}数据异常，部门为空！",token.getUsername());
            DeptDTO deptDTO = deptService.getDept(departList.get(0));
            entity.setDepartmentNo(deptDTO.getDepartmentNo());
            entity.setDepartmentNos(deptDTO.getDepartmentNos());
            entity.setDepartmentName(deptDTO.getDepartmentName());
        }
        entity.setCompanyNo(token.getCompanyNo());

        JSONObject jsonObject = new JSONObject();

        return chargeUrgingService.insertManage(entity, jsonObject);
    }


    @ReqMapping("/urgingUserList")
    public Object urgingUserList(JSONObject jsonObject){

        return Result.success(chargeUrgingService.urgingUserList(jsonObject));
    }


    @Bean(copy=true)
    @HasPermission("pay:charge:urging:edit")
    @ReqMapping("/update")
    public Object update(ChargeUrgingConfig entity) throws Exception {

        return chargeUrgingService.update(entity);
    }


    @HasPermission("pay:charge:urging:edit")
    @ReqMapping("/delete")
    public Object delete(ChargeUrgingConfig entity) {

        return chargeUrgingService.deleteById(entity.getId());
    }


    @ReqMapping("/get")
    public Object get(ChargeUrgingConfig entity) {

        return Result.success(entity);
    }


    @ReqMapping("/setStatus")
    @HasPermission("pay:charge:urging:edit")
    public Object setStatus(ChargeUrgingConfig entity) throws Exception {
        entity.setStatus(!entity.isStatus());
        chargeUrgingService.update(entity);
        return Result.success();
    }


    @ReqMapping("/getTypeEnum")
    public Object getTypeEnum() {

        TemplateType templateType = TemplateType.PAY_C_TASK_REMIND;
        try {
            JSONObject configJson = doveClient.post("/crm/message/global/config/service/get", (http) -> {
                http.addParam("templateType", templateType.getId());
            });
            if (configJson.getIntValue("code") == 200) {
                List<Map<String, String>>  mapObj = new ArrayList<>();
                JSONObject configDataJson = configJson.getJSONObject("data");
                for (UrgingTypeEnum typeEnum : UrgingTypeEnum.values()) {
                    Map<String, String> map = new LinkedHashMap<>();
                    map.put("id", typeEnum.getId());
                    map.put("desc", typeEnum.getDesc());
                    map.put("template", templateType.getDesc());

                    if (UrgingTypeEnum.MSG_SITE == typeEnum) {
                        map.put("status", configDataJson.getString("innerSend"));

                        JSONObject tempJson = configDataJson.getJSONObject("messageTemplateInner");
                        if (Objects.nonNull(tempJson)) {
                            map.put("title", tempJson.getString("title"));
                            map.put("content", tempJson.getString("content"));
                            map.put("messageNo", tempJson.getString("id"));
                        }
                    } else if (UrgingTypeEnum.MSG_PUSH == typeEnum) {
                        map.put("status", configDataJson.getString("wxchatSend"));

                        String wxchatTemplate = configDataJson.getString("wxchatTemplate");
                        JSONObject wxchatJson = doveClient.post("/wechat/template/setting/service/get", (http) -> {
                            http.addParam("id", wxchatTemplate);
                        });
                        if (configJson.getIntValue("code") == 200) {
                            JSONObject wxchatDataJson = wxchatJson.getJSONObject("data");
                            if (Objects.nonNull(wxchatDataJson)) {
                                map.put("title", wxchatDataJson.getString("name"));
                                map.put("content", wxchatDataJson.getString("templateNo"));
                                map.put("messageNo", wxchatDataJson.getString("id"));
                            } else {
                                map.put("content", null);
                            }
                        } else {
                            map.put("content", null);
                        }
                    } else if (UrgingTypeEnum.MSG_PHONE == typeEnum) {
                        map.put("status", configDataJson.getString("smsSend"));

                        JSONObject tempJson = configDataJson.getJSONObject("messageTemplateSms");
                        if (Objects.nonNull(tempJson)) {
                            map.put("title", tempJson.getString("title"));
                            map.put("content", tempJson.getString("content"));
                            map.put("messageNo", tempJson.getString("id"));
                        }
                    } else {
                        // continue
                        map.put("status", "false");
                        map.put("templateNo", null);
                    }

                    mapObj.add(map);
                }

                return Result.success(mapObj);
            }
        } catch (Exception e){
            logger.error(e.getMessage(), e);
        }

        return Result.success(Arrays.asList(UrgingTypeEnum.values()));
    }



}
